<template>
  <a-space direction="vertical" style="margin-top: 15vh">
    <a-space direction="horizontal">
      <span>Username :</span>
      <a-input v-model:value="username" style="width: 20vw"/>
    </a-space>

    <a-space direction="horizontal">
      <span>Password :&nbsp;</span>
      <a-input v-model:value="password" type="password" style="width: 20vw"/>
    </a-space>

    <a-space direction="horizontal" style="margin-top: 20px">
      <a-button type="primary" @click="handleSubmit" :loading="loading">Login</a-button>
      <a-button @click="handleRegeister">Register</a-button>
    </a-space>
  </a-space>
</template>

<script>
import axiosInstance from "@/axios/axios.js";
import {message} from "ant-design-vue";

export default {
  data() {
    return {
      username: '',
      password: '',
      loading: false
    };
  },
  methods: {
    handleRegeister() {
      this.$router.push({
        path: '/register',
      });
    },
    async handleSubmit() {
      if (!this.username || !this.password) {
        message.warning('请输入用户名和密码');
        return;
      }

      this.loading = true;
      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/authenticate",  // 移除/api前缀
          data: {
            username: this.username,
            password: this.password,
          },
        });

        if (response.data.code === 401) {
          message.error("用户名或密码错误！");
          return;
        }

        console.log('Login Response:', response.data);

        // 设置cookie
        this.$cookies.set('jwt', response.data.data.jwt);
        this.$cookies.set('username', this.username);
        this.$cookies.set('userAddress', response.data.data.userAddress);

        // 验证cookie是否设置成功
        const jwt = this.$cookies.get('jwt');
        const userAddress = this.$cookies.get('userAddress');
        console.log('JWT Token after set:', jwt);
        console.log('User Address after set:', userAddress);

        // 设置登录状态
        sessionStorage.setItem("isLogin", "true");

        message.success('登录成功');

        // 等待一下确保cookie设置完成
        await new Promise(resolve => setTimeout(resolve, 100));

        // 跳转前再次验证
        if (!this.$cookies.get('jwt') || !this.$cookies.get('userAddress')) {
          throw new Error('Login information not set properly');
        }

        this.$router.push({
          path: '/MyData/ExperimentSet',
        });
      } catch (error) {
        console.error("登录失败:", error);
        message.error(error.response?.data?.message || '登录失败，请重试');
      } finally {
        this.loading = false;
      }
    },
  },
  // 组件创建时检查登录状态
  created() {
    if (sessionStorage.getItem("isLogin") && this.$cookies.get('jwt')) {
      this.$router.push('/MyData/ExperimentSet');
    }
  }
};
</script>

<style scoped>
.ant-input {
  width: 100%;
}
</style>
